package com.matrix.draft.helloworld.sys;

public class DoMovingThread extends Thread{

    private SmartRobot smartRobot;

    private final Object lock = new Object();

    private boolean pause = true;

    private DoMovingThread(){}

    public DoMovingThread(SmartRobot smartRobot) throws InterruptedException {
        this.smartRobot = smartRobot;
        lock.wait();
    }

    private void doMoving(){
        System.out.println("执行了一次");
    }


    /**
     * 调用该方法实现线程的暂停
     */
    public void pauseThread(){
        pause = true;
    }


    /*
    调用该方法实现恢复线程的运行
     */
    public void resumeThread(){
        pause =false;
        synchronized (lock){
            lock.notify();
        }
    }

    /**
     * 这个方法只能在run 方法中实现，不然会阻塞主线程，导致页面无响应
     */
    private void onPause() {
        synchronized (lock) {
            try {
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void run() {
        while(true){
            while (pause){
                onPause();
            }
            try {
                doMoving();
                Thread.sleep(50);
            }catch (Exception e){
                e.printStackTrace();
                break;
            }
        }
    }
}
